<template>
  <div v-if="isShow">
    <transition name="fade">
      <div class="upload-progress">
        <div class="progress-bar-container">
          <div class="progressTopLeft">
            <div class="icons">
              <el-icon :size="28" :color="uploadStatus.color"
                :class="uploadStatus.icon === 'uploading' ? 'is-loading' : ''">
                <Loading v-if="uploadStatus.icon === 'uploading'" />
                <CircleCheckFilled v-else-if="uploadStatus.icon === 'success'" />
                <CircleCloseFilled v-else-if="uploadStatus.icon === 'failed'" />
                <WarningFilled v-else-if="uploadStatus.icon === 'warning'" />
              </el-icon>
            </div>
            <div class="text">
              <p>{{ uploadStatus.statusText }}</p>
            </div>
          </div>

          <div class="progressTopRight">
            <el-icon :size="26" style="margin-right: 10px;" @click="retractClick">
              <ArrowDown v-if="isExpanded" />
              <ArrowUp v-else />
            </el-icon>
            <el-icon :size="26" @click="closeClick">
              <Close />
            </el-icon>
          </div>
        </div>

        <div :class="isExpanded ? 'progress_expand' : 'progress_colsed'">
          <div class="fileContent" v-if="isExpanded">
            <div class="midTip">
              <div class="statusDiv" v-if="uploadingNum > 0">
                <div class="fileNum">正在上传{{ uploadingNum }}个任务，</div>
                <div class="totalSize">总大小{{ formatSize(uploadSize) }}</div>
              </div>
              <div class="statusDiv" v-if="successNum > 0 && (failedNum > 0 || uploadingNum === 0)">
                <div class="fileNum">已上传{{ successNum }}个任务，</div>
                <div class="totalSize">总大小{{ formatSize(successSize) }}</div>
              </div>
              <div class="statusDiv" v-if="failedNum > 0 && uploadingNum === 0 && successNum === 0">
                <div class="fileNum">已失败{{ failedNum }}个任务，</div>
                <div class="totalSize">总大小{{ formatSize(failSize) }}</div>
              </div>

            </div>
            <div class="fileItemList">
              <div class="fileItem" v-for="(v, i) in fileList" :key="'id' + i" v-show="v.typeName === 'file'">
                <svg-icon :icon-class="selectSvgIcons(v)"
                  style="font-size: 28px;vertical-align: middle;margin-right: 6px;margin-left: 18px;"></svg-icon>
                <div class="fileMid">
                  <div class="name">
                    <el-tooltip class="itemTip" effect="dark" :content="v.name" placement="top">
                      <div class="fileText">{{ v.name }}</div>

                    </el-tooltip>

                    <!-- <div class="tip" v-if="v.status === 'excluded' && v.size != 0">{{ $t('newUpload.msg5') }}</div>
              <div class="tip" v-if="v.status === 'excluded' && v.size == 0">{{ $t('newUpload.msg4') }}</div>
              <div class="tip" v-if="v.status === 'canceled' && v.progress == 0">取消上传</div> -->
                  </div>
                  <!-- <div class="size">{{ formatSize(v.loaded) + '/' + formatSize(v.size) }}</div> -->
                  <div class="size">{{ formatSize(v.size) }}</div>
                </div>

                <div class="progressItem" v-if="v.status !== 'excluded' || v.progress !== 0">
                  <el-progress type="circle" class="custom-circle-progress" :width="40"
                    :percentage="v.progress"></el-progress>

                </div>
                <!-- <div v-if="v.status === 'waiting' || v.status === 'uploading'">
              <el-icon>
                <Close />
              </el-icon>
            </div> -->
              </div>
              <div class="folderItem" v-for="(item, index) in fileList" :key="'id' + index"
                v-show="item.typeName === 'folder'">
                <div class="incoLf">
                  <svg-icon :icon-class="selectSvgIcons(item)"
                    style="font-size: 28px;vertical-align: middle;margin-right: 6px;margin-left: 18px;"></svg-icon>
                  <div class="fileMid">
                    <div class="name">
                      <el-tooltip class="itemTip" effect="dark" :content="item.folderName" placement="top">
                        <div class="fileText">{{ item.folderName }}</div>
                      </el-tooltip>

                      <!-- <div class="tip" v-if="v.status === 'excluded' && v.size != 0">{{ $t('newUpload.msg5') }}</div>
              <div class="tip" v-if="v.status === 'excluded' && v.size == 0">{{ $t('newUpload.msg4') }}</div>
              <div class="tip" v-if="v.status === 'canceled' && v.progress == 0">取消上传</div> -->
                    </div>
                    <div class="size">{{ formatSize(item.size) }}</div>
                  </div>
                </div>
                <div class="progressItem">
                  <el-progress type="circle" class="custom-circle-progress" :width="40"
                    :percentage="item.progress"></el-progress>

                </div>
              </div>
            </div>

          </div>
        </div>
      </div>
    </transition>
    <transition name="cancel-fade">
      <div class="dialog">
        <el-dialog :visible.sync="dialogVisible" title="取消上传" width="20%" top="24vh" :show-close="false"
          :before-close="handleClose">
          <span>上传尚未完成，要取消所有正在上传的文件吗？</span>
          <span slot="footer" class="dialog-footer">
            <el-button @click="cancelDialog">取消</el-button>
            <el-button type="primary" @click="determineDialog">确定</el-button>
          </span>
        </el-dialog>
      </div>
    </transition>
  </div>
</template>


<script lang="ts" setup>
import { Loading } from '@element-plus/icons-vue';

import { ref } from 'vue'



const props = defineProps<{
  fileData: Record<string, any> | null
}>()






const isShow = ref(false)
const isExpanded = ref(true)
const fileList = ref([])

const successNum = ref(0)
const failedNum = ref(0)
const uploadingNum = ref(0)

const uploadSize = ref(0)
const successSize = ref(0)
const failSize = ref(0)
// 上传状态
const uploadStatus = reactive({
  statusText: "文件上传中....",
  color: "#409EFF",
  icon: "uploading"
})
const { proxy } = getCurrentInstance() as any

const dialogVisible = ref(false)




watch(
  () => props.fileData,
  (newFileData) => {

    // 当 fileData 发生变化时可以在这里处理
    newFileData.forEach((newFile) => {
      const existingFileIndex = fileList.value.findIndex(file => file.id === newFile.id)
      if (existingFileIndex !== -1) {
        // 如果文件已经存在，根据 id 更新已有文件
        fileList.value[existingFileIndex] = { ...fileList.value[existingFileIndex], ...newFile }
      } else {
        // 如果文件不存在，则添加新文件
        fileList.value.push({ ...newFile, addedTime: Date.now() })
      }
    })
    fileList.value.sort((a, b) => b.addedTime - a.addedTime)
    updateUploadStatus()
    console.log(uploadStatus.icon,'123')
  },
  { deep: true } // 深度监听，确保可以监听到数组内部对象的变化
)

const updateUploadStatus = () => {
  const allFiles = fileList.value
  const allSuccess = allFiles.every(file => file.status === 'success')
  successNum.value = allFiles.filter(file => file.status === 'success').length
  successSize.value = allFiles.filter(file => file.status === 'success').reduce((acc, file) => acc + file.size, 0)
  const allFailed = allFiles.every(file => file.status === 'failed')
  failedNum.value = allFiles.filter(file => file.status === 'failed').length
  failSize.value = allFiles.filter(file => file.status === 'failed').reduce((acc, file) => acc + file.size, 0)
  uploadingNum.value = allFiles.filter(file => file.status === 'uploading').length

  uploadSize.value = allFiles.filter(file => file.status === 'uploading').reduce((acc, file) => acc + file.size, 0)
  // 部分上传失败
  const partFailed = allFiles.some(file => file.status === 'failed')



  if (allSuccess) {
    uploadStatus.statusText = '文件全部上传成功'
    uploadStatus.color = '#67C23A'
    uploadStatus.icon = 'success'
  } else if (allFailed) {
    uploadStatus.statusText = '文件全部上传失败'
    uploadStatus.color = '#F56C6C'
    uploadStatus.icon = 'failed'
  } else if (partFailed) {
    uploadStatus.statusText = '部分文件上传失败'
    uploadStatus.color = '#E6A23C'
    uploadStatus.icon = 'warning'
  } else {
    uploadStatus.statusText = '文件上传中...'
    uploadStatus.color = '#409EFF'
    uploadStatus.icon = 'uploading'
  }

}


const selectSvgIcons = (v: any) => {
  return proxy.$yuUtils.selectSvgIcon(v)
}
const formatSize = (size: number) => {
  return proxy.$yuUtils.filterSizeUnit(size)
}






const showProgress = () => {
  isShow.value = true
  isExpanded.value = true
}
const hideProgress = () => {
  isShow.value = false
}
const retractClick = () => {
  isExpanded.value = !isExpanded.value
}
const closeClick = () => {
  isShow.value = false
  isExpanded.value = true
  fileList.value = []
  proxy.$emit('clearFileData') // 通知父组件清空数据
  // const allUploaded = fileList.value.every(file => file.status === 'success' && file.process === 100)
  // if (allUploaded) {
  //     isShow.value = false
  //     isExpanded.value = true
  //     fileList.value = []
  //     proxy.$emit('clearFileData') // 通知父组件清空数据
  // } else {
  //     dialogVisible.value = true
  // }

}

const handleClose = (done: () => void) => {

}
const cancelDialog = (done: () => void) => {

}
const determineDialog = (done: () => void) => {

}

defineExpose({
  showProgress,
  hideProgress
})
</script>



<style lang="scss" scoped>
:deep(.progressItem) {
  display: flex;
  justify-content: flex-end;
  margin-right: 60px;

  .el-progress__text {
    font-size: 12px !important;
    left: 40px !important;
  }
}

p {
  margin: 0;
}

.upload-progress {
  position: fixed;
  right: 30px;
  bottom: 40px;
  z-index: 9998;
  background-color: white;
  border: 1px solid rgb(222, 224, 227);
  width: 420px;
  // height: 200px;
  border-radius: 8px;



  .progress-bar-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 68px;
    padding: 0px 10px;

    .progressTopLeft {
      display: flex;
      align-items: center;
      height: 68px;

      .icons {
        width: 28px;
        height: 28px;
      }

      .text {
        font-size: 16px;
        margin-left: 20px;
        color: #333;
      }
    }

    .progressTopRight {
      display: flex;
      align-items: center;

      .el-icon {
        cursor: pointer;
      }
    }
  }

  .fileContent {
    width: 100%;
    // max-height: 280px;
    // overflow-y: auto;
    // will-change: transform;
    // direction: ltr;

    .file-collapse {
      width: 100%;
      position: relative;
      // style="display: flex;align-items: center;justify-content: space-between;height:56px"


    }

    .fileItem {
      width: 100%;
      height: 56px;
      display: flex;
      align-items: center;
      position: relative;
      // background-color: green;

      // i {
      //   font-size: 40px;
      //   padding-left: 20px;
      // }

      .fileMid {
        // width: 220px;
        margin-left: 20px;
        flex: 1;
        display: flex;
        flex-direction: column;
        // overflow: hidden;
        position: relative;

        .name {
          font-size: 14px;
          color: #333;
          height: 20px;
          line-height: 20px;

          display: flex;

          .fileText {
            white-space: nowrap;
            /* Prevent text wrapping */
            overflow: hidden;
            /* Hide overflowed content */
            text-overflow: ellipsis;
            /* Add ellipsis (...) */
            max-width: 180px;
            /* Set a maximum width for the element */
            display: inline-block;
            /* Required for text-overflow to work */
          }

          .tip {
            color: #e22e28;
            font-size: 14px;
            margin-left: 10px;
          }
        }

        .size {
          font-size: 12px;
          color: #666;
          height: 18px;
          line-height: 18px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }

      .iconItem {
        line-height: 38px;
        margin-right: 10px;
      }
    }

    .folderItem {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 56px;

      .incoLf {
        display: flex;
        align-items: center;

        .fileMid {
          margin-left: 20px;

          .name {
            font-size: 14px;
            color: #1f2329;
          }

          .size {
            font-size: 12px;
            margin-top: 6px;
            color: #646273;

          }
        }
      }

      &:hover {
        background-color: #f5f6f7;
      }
    }

    .fileItem:hover::before {
      cursor: pointer;
      content: "";
      display: block;
      position: absolute;
      top: 2px;
      left: 4px;
      right: 4px;
      bottom: 0;
      z-index: 1;
      transform: 0.3s;
      border-radius: 6px;
      background-color: rgba(31, 35, 41, 0.08);
    }


  }

  .midTip {
    position: relative;
    width: 100%;
    height: 40px;
    display: flex;
    align-items: center;
    background-color: rgb(245, 246, 247);
    padding-left: 20px;

    .statusDiv {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100%;

      div {
        font-size: 14px;
        color: #333;
        letter-spacing: 1.5px;
      }
    }
  }

  .fileItemList {
    max-height: 225px;
    overflow-y: auto;
    will-change: transform;
    direction: ltr;
  }
}
</style>